import React, { Component } from 'react';
import { ImageBackground, ScrollView, View, Image, StatusBar, Text, TouchableOpacity, FlatList, RefreshControl, DeviceEventEmitter } from 'react-native';
import TabBarTitle from '../components/TabBarTitle';
import { TabBarImage, TabBarAnimationImage } from '../components/TabBarImage';
import Colors from '../constants/Colors';
import { statusBarHeight, titleHeight, width, unitWidth } from '../constants/AdapterUtil';
import { MyHeader } from '../components/MyHeader';
import { SubmitButton8, AddButton, ReduceButton, SubmitButton9, SubmitButton10, SubmitButton4, SubmitButton13, SubmitButton15 } from '../components/Button';
import { api_member_cart_get_list, api_order_workorder_orderDetail, api_order_workorder_deleteOrder, api_order_workorder_under_line_Confirm, api_order_workorder_orderpay } from '../constants/HttpServices';
import { postFetch } from '../constants/HttpExtension';
import MyListView from '../components/MyListView';
import { DeleteTextView } from '../components/MyTextView';
import { CommonModal2, BottomPayModal, CommonModal3, BottomReasonModal } from '../components/Modal';
import { MeItem, IconItem, OrderDetailHeaderItem, Item3, RatingItem } from '../components/Item';
import { MyInput1 } from '../components/Input';
import TextUtil from '../constants/TextUtil';
import Video from 'react-native-video';
import { show } from '../constants/Toast';
import { contactBrowser } from '../constants/Gobrowser';
import { wxPay } from '../constants/Pay';

export default class NeedsOrderDetailScreen extends Component {
    constructor(props) {
        super(props)
        this.no = this.props.navigation.getParam('no', '0')
        this.state = {
            online: 0,//是否在线

            progress: 0,//当前订单进度

            info: {},

            isFail: false,

            // lc1: ['雇主下单', '确认合作', '确认收货', '评价'],
            lc2: ['雇主下单', '确认合作', '开工生产', '收货', '评价'],
            // list: ['https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png',
            //     'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png']
        }
    }

    componentDidMount() {
        this.props.navigation.addListener('didFocus', payload => {
            this.getData();
        })
    }

    render() {
        return (
            <View style={{ flex: 1, backgroundColor: Colors.colorF7 }}>
                <MyHeader title='订单详情' leftImg={require('../res/ic_arrow_left.png')} leftClick={() => { this.props.navigation.pop() }} />
                {/* {this.state.online == 0 ? this.getOutLineView() : this.getOnLineView()} */}
                {this.getOnLineView()}
                <View style={{
                    width: width, height: 50 * unitWidth, bottom: 0 * unitWidth, position: 'absolute',
                    flexDirection: 'row', alignItems: 'center', justifyContent: 'center', backgroundColor: Colors.white
                }}>
                    {this.getBottonBtn(this.state.info)}
                </View>

                <CommonModal2 ref='CommonModal1' title='是否删除订单？' comfirmText='确定' cancelText='取消'
                    cancelClick={() => {

                    }}
                    comfirmClick={() => {
                        this.deleteOrder();
                    }} />

                <CommonModal2 ref='CommonModal2' title='是否确认收货？' comfirmText='确定' cancelText='取消'
                    cancelClick={() => {

                    }}
                    comfirmClick={() => {
                        this.confirmReceive();
                    }} />
                <BottomPayModal ref='BottomPayModal' onClick={(index) => {
                    this.pay(index);
                }} />
            </View>
        )
    }

    getOutLineView() {
        return (
            <ScrollView style={{ marginBottom: 50 * unitWidth }}>
                <OrderDetailHeaderItem list={this.state.lc1} progress={this.state.progress} />
                <View style={{
                    width: width, alignSelf: 'center',
                    backgroundColor: Colors.white, paddingVertical: 10 * unitWidth
                }}>
                    <Item3 style={{ marginTop: 22 * unitWidth, marginLeft: 17 * unitWidth }} text='报价详情' />
                    <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>服务商：{this.state.info.merchname}</Text>
                    <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>报价金额：<Text style={{ color: Colors.colorRed }}>￥{this.state.info.total_price}</Text></Text>
                    <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>交货日期：{this.state.info.delivery_date}</Text>
                </View>
                <View style={{
                    width: width, alignSelf: 'center',
                    backgroundColor: Colors.white, paddingVertical: 10 * unitWidth, marginTop: 5 * unitWidth
                }}>
                    <Item3 style={{ marginLeft: 17 * unitWidth }} text='订单信息' />
                    <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>订单编号：{this.state.info.out_trade_no}</Text>
                    <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>创建时间：{this.state.info.createtime}</Text>
                    <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>订单状态：<Text style={{ color: Colors.colorOrange }}>待收货</Text></Text>
                </View>
                {this.state.progress > 2 ?
                    <View style={{
                        width: width, alignSelf: 'center',
                        backgroundColor: Colors.white, paddingVertical: 10 * unitWidth, marginTop: 5 * unitWidth
                    }}>
                        <Item3 style={{ marginLeft: 17 * unitWidth }} text='评价' />
                        <View style={{ flexDirection: 'row', marginTop: 5 * unitWidth }}>
                            <Text style={{ fontSize: 14, marginLeft: 35 * unitWidth }}>评价服务商：</Text>
                            <View>
                                <RatingItem style={{ marginTop: 0 * unitWidth }} progress={2} text='完成质量' />
                                <RatingItem style={{ marginTop: 3 * unitWidth }} progress={2} text='完成速度' />
                                <RatingItem style={{ marginTop: 3 * unitWidth }} progress={2} text='服务态度' />
                            </View>
                        </View>
                        <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>更多评价：完成质量高，服务态度非常好</Text>
                        <View style={{
                            alignSelf: 'stretch',
                            alignItems: 'center',
                            flexDirection: 'row',
                            flexWrap: 'wrap',
                            marginLeft: 20 * unitWidth, marginVertical: 15 * unitWidth
                        }}>
                            {this.getImageListView()}
                        </View>
                    </View> : null}
                <View style={{
                    width: 345 * unitWidth, height: 50 * unitWidth, alignSelf: 'center', top: 82 * unitWidth, position: 'absolute',
                    backgroundColor: Colors.white, borderRadius: 10, flexDirection: 'row', alignItems: 'center'
                }}>
                    <Text style={{ color: Colors.black, fontSize: 16, fontWeight: 'bold', marginLeft: 15 * unitWidth }}>需求详情</Text>
                    <Image source={require('../res/me_back.png')} style={{ width: 7 * unitWidth, height: 12 * unitWidth, position: 'absolute', right: 15 * unitWidth }} />
                </View>
            </ScrollView>
        )
    }

    getOnLineView() {
        return (
            <ScrollView style={{ marginBottom: 50 * unitWidth }}>
                <OrderDetailHeaderItem list={this.state.lc2} progress={this.state.progress} />
                <View style={{
                    width: width, alignSelf: 'center',
                    backgroundColor: Colors.white, paddingVertical: 10 * unitWidth
                }}>
                    <Item3 style={{ marginTop: 22 * unitWidth, marginLeft: 17 * unitWidth }} text='报价详情' />
                    <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>服务商：{this.state.info.merchname}</Text>
                    <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>报价金额：<Text style={{ color: Colors.colorRed }}>￥{this.state.info.total_price}</Text></Text>
                    <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>交货日期：{this.state.info.delivery_date}</Text>
                </View>
                <View style={{
                    width: width, alignSelf: 'center',
                    backgroundColor: Colors.white, paddingVertical: 10 * unitWidth, marginTop: 5 * unitWidth
                }}>
                    <Item3 style={{ marginLeft: 17 * unitWidth }} text='订单信息' />
                    <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>订单编号：{this.state.info.out_trade_no}</Text>
                    <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>创建时间：{this.state.info.createtime}</Text>
                    {this.state.progress > 1 ?
                        <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>服务商确认时间：{this.state.info.confirm_time}</Text>
                        : null}
                    {this.state.progress > 3 ?
                        <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>服务商送货时间：{this.state.info.confirm_delivery_time}</Text>
                        : null}
                    <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>订单状态：<Text style={{ color: Colors.colorOrange }}>{this.getStatuText(this.state.info)}</Text></Text>
                </View>
                {this.state.progress > 2 && this.state.online == 1 ?
                    <View style={{
                        width: width, alignSelf: 'center',
                        backgroundColor: Colors.white, paddingVertical: 10 * unitWidth, marginTop: 5 * unitWidth
                    }}>
                        <Item3 style={{ marginLeft: 17 * unitWidth }} text='支付信息' />
                        <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>支付方式：<Text style={{ color: Colors.colorOrange }}>{this.state.info.type == 1 ? '全款（低于5万元）' : '5-5(5成定金，收货确认5成)'}</Text></Text>
                        <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>预支付：<Text style={{ color: Colors.colorOrange }}>￥{this.state.info.pay_price}</Text></Text>
                        {this.state.progress > 4 ?
                            <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>收货确认支付：<Text style={{ color: Colors.colorOrange }}>￥{this.state.info.two_pay_price}</Text></Text>
                            : null}
                    </View> : null}
                {this.state.info.assess ?
                    <View style={{
                        width: width, alignSelf: 'center',
                        backgroundColor: Colors.white, paddingVertical: 10 * unitWidth, marginTop: 5 * unitWidth
                    }}>
                        <Item3 style={{ marginLeft: 17 * unitWidth }} text='评价' />
                        <View style={{ flexDirection: 'row', marginTop: 5 * unitWidth }}>
                            <Text style={{ fontSize: 14, marginLeft: 35 * unitWidth }}>评价服务商：</Text>
                            <View>
                                <RatingItem style={{ marginTop: 0 * unitWidth }} progress={this.state.info.assess.quality} text='完成质量' />
                                <RatingItem style={{ marginTop: 3 * unitWidth }} progress={this.state.info.assess.speed} text='完成速度' />
                                <RatingItem style={{ marginTop: 3 * unitWidth }} progress={this.state.info.assess.attitude} text='服务态度' />
                            </View>
                        </View>
                        <Text style={{ fontSize: 14, marginTop: 5 * unitWidth, marginLeft: 35 * unitWidth }}>更多评价：{this.state.info.assess.content}</Text>
                        {this.state.info.assess.is_img == '1' ?
                            <View style={{
                                alignSelf: 'stretch',
                                alignItems: 'center',
                                flexDirection: 'row',
                                flexWrap: 'wrap',
                                marginLeft: 20 * unitWidth, marginVertical: 15 * unitWidth
                            }}>
                                {this.getImageListView(JSON.parse(this.state.info.assess.imgOrVideo))}
                            </View> : <Video
                                ref={(ref) => this.videoPlayer = ref}
                                source={{ uri: JSON.parse(this.state.info.assess.imgOrVideo)[0] }}
                                rate={1.0}
                                volume={1.0}
                                muted={false}
                                paused={false}
                                resizeMode='contain'
                                playWhenInactive={false}
                                playInBackground={false}
                                ignoreSilentSwitch={'ignore'}
                                progressUpdateInterval={250.0}
                                onLoad={this._onLoaded}
                                style={{
                                    width: 345 * unitWidth, height: 150 * unitWidth, backgroundColor: Colors.black, marginVertical: 15 * unitWidth,
                                    alignSelf: 'center'
                                }} />}
                    </View> : null}
                <TouchableOpacity style={{
                    width: 345 * unitWidth, height: 50 * unitWidth, alignSelf: 'center', top: 82 * unitWidth, position: 'absolute',
                    backgroundColor: Colors.white, borderRadius: 10, flexDirection: 'row', alignItems: 'center'
                }} activeOpacity={1} onPress={() => {
                    this.props.navigation.navigate('DemandDetail', { id: this.state.info.work_order_id })
                }}>
                    <Text style={{ color: Colors.black, fontSize: 16, fontWeight: 'bold', marginLeft: 15 * unitWidth }}>需求详情</Text>
                    <Image source={require('../res/me_back.png')} style={{ width: 7 * unitWidth, height: 12 * unitWidth, position: 'absolute', right: 15 * unitWidth }} />
                </TouchableOpacity>
            </ScrollView>
        )
    }

    getBottonBtn(item) {
        if (item.is_cooperation == '0') {
            return null
        } else if (item.is_cooperation == '1' && item.is_contract == '0') {
            return (<SubmitButton15 style={{}} text='去签署电子合同'
                onPress={() => {
                    this.props.navigation.navigate('SigningContract', { no: this.no })
                }} />)
        } else if (item.is_cooperation == '2') {
            return (<SubmitButton15 style={{}} text='请重新发布需求'
                onPress={() => {
                    // this.props.navigation.navigate('SigningContract', { id: this.state.info.id })
                }} />)
        } else if (item.status == '0') {
            return (<SubmitButton4 style={{}} text='支付'
                onPress={() => {
                    this.refs.BottomPayModal.showModal();
                }} />)
        } else if (item.status == '1') {
            return null
        } else if (item.status == '3') {
            return (<SubmitButton4 style={{}} text='确认收货'
                onPress={() => { this.refs.CommonModal2.showModal(); }} />)
        } else if (item.status == '2') {
            if (item.is_employer_comment == '0') {
                return (<SubmitButton4 text='评价' onPress={() => { this.props.navigation.navigate('EvaluateService', { no: this.no }) }} />)
            } else {
                return (<SubmitButton13 text='删除订单' onPress={() => { this.refs.CommonModal1.showModal(); }} />)
            }
        } else if (item.status == '4') {
            return (<SubmitButton13 text='删除订单' onPress={() => { this.refs.CommonModal1.showModal(); }} />)
        } else if (item.status == '5') {
            return null
        }
    }

    getStatuText(item) {
        if (item.is_cooperation == '0') {
            return '待服务商确定合作'
        } else if (item.is_cooperation == '1' && item.is_contract == '0') {
            return '待签署电子合同'
        } else if (item.is_cooperation == '2') {
            return '交易失败（服务商拒绝合作）'
        } else if (item.status == '0') {
            return '待支付'
        } else if (item.status == '1') {
            return '待服务商交货'
        } else if (item.status == '3') {
            return '待确认'
        } else if (item.status == '2') {
            return '已完成'
        } else if (item.status == '4') {
            return '已完成'
        } else if (item.status == '5') {
            return '交易失败（超过规定时间）'
        }
    }

    getImageListView(list) {
        let views = [];
        if (list) {
            for (let i = 0, len = list.length; i < len; i++) {
                let item = list[i];
                views.push(
                    <TouchableOpacity key={i} style={{ width: 105 * unitWidth, height: 72 * unitWidth, marginTop: 10 * unitWidth, marginRight: 10 * unitWidth }}
                        activeOpacity={0.7} onPress={() => { this.props.navigation.navigate('BigImageList', { imageList: list }) }}>
                        <Image
                            style={{ width: 105 * unitWidth, height: 72 * unitWidth }}
                            source={{ uri: item }} resizeMode='cover' />
                    </TouchableOpacity>
                );
            }
        }
        return views
    }

    getData() {
        let params = {
            out_trade_no: this.no
        }
        postFetch(api_order_workorder_orderDetail, params, {
            success: (response) => {
                let progress = 0;
                let online = response.result.payment_type == '0' ? 0 : 1;
                if (response.result.is_cooperation == '0') {
                    progress = 1
                } else if (response.result.is_cooperation == '1' && response.result.is_contract == '0') {
                    progress = 2
                } else if (response.result.is_cooperation == '2') {
                    progress = 1
                } else if (response.result.status == '0') {
                    progress = 2
                } else if (response.result.status == '1') {
                    progress = 3
                } else if (response.result.status == '3') {
                    progress = 4
                } else if (response.result.status == '2') {
                    progress = 5
                } else if (response.result.status == '4') {
                    progress = 5
                } else if (response.result.status == '5') {
                    progress = 4
                }
                this.setState({
                    info: response.result,
                    online: online,
                    progress: progress
                })
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    deleteOrder() {
        let params = {
            out_trade_no: this.no
        }
        postFetch(api_order_workorder_deleteOrder, params, {
            success: (response) => {
                show('删除成功');
                this.props.navigation.pop();
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //确认收货
    confirmReceive() {
        let params = {
            out_trade_no: this.no
        }
        postFetch(api_order_workorder_under_line_Confirm, params, {
            success: (response) => {
                if (response.result.status == '1') {
                    this.refs.BottomPayModal.showModal();
                } else {
                    show('确认成功');
                    this.getData();
                }
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    pay(type) {
        let params = {
            'out_trade_no': this.no,
            'payment_type': type,
        }
        postFetch(api_order_workorder_orderpay, params, {
            success: (response) => {
                if (type == 1) {
                    wxPay(response.result, {
                        success: () => {
                            show('支付成功');
                            this.props.navigation.pop();
                        },
                        fail: () => {

                        }
                    })
                } else if (type == 2) {
                    contactBrowser(response.result.url)
                } else if (type == 3) {
                    show('支付成功');
                    this.getData()
                }
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }
}